import { format } from 'date-fns';
import html2canvas from 'html2canvas';

// 日期格式化
export const timeFormat = (date, formatString = 'yyyy-MM-dd HH:mm:ss') => {
  if (!date) {
    return '请传入时间戳';
  }
  // 由于返回的时间戳是除以了1000之后，在这做判断，如果10位时间戳则*1000
  if (String(date).length === 10) {
    date *= 1000;
  }
  return format(Number(date), formatString);
};

// 将秒转时分秒
export const formatSeconds = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

// 下载文件
export const downloadFile = (url) => {
  // 利用a标签下载文件
  const a = document.createElement('a');
  a.setAttribute('download', url);
  a.setAttribute('href', url);
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 引入图片
export const requireImg = (imgPath) => {
  return new URL(`../assets/images/${imgPath}`, import.meta.url).href;
};

// 全屏
export const fullscreen = (element) => {
  if (element.requestFullscreen) {
    element.requestFullscreen(); // 浏览器支持全屏API
  } else if (element.mozRequestFullScreen) {
    // Firefox 早期的全屏方法
    element.mozRequestFullScreen(); // 早期的全屏方法，需要前缀 "moz"
  } else if (element.webkitRequestFullscreen) {
    // Chrome, Safari 和 Opera 的当前全屏方法
    element.webkitRequestFullscreen(); // 当前全屏方法，需要前缀 "webkit"
  } else if (element.msRequestFullscreen) {
    // IE/Edge 全屏方法
    element.msRequestFullscreen(); // IE/Edge 全屏方法，需要前缀 "ms"
  }
};

// 随机len位字母数字字符串
export const randomCode = (len = 8) => {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for (var i = 0; i < len; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
};

// 将阿拉伯数字转为一二三四五这样的形式
export const numberToUppercase = (number) => {
  if (!number || (typeof number !== 'number' && typeof number !== 'string')) return;
  const arr = String(number).split('');
  const chineseNumber = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
  let result = '';
  arr.forEach((item) => {
    result += chineseNumber[Number(item)];
  });
  return result;
};

// 给定一个数组类型的tree数据，会自动在每个节点添加levle属性
export const getNodeLevel = (listTree) => {
  const list = JSON.parse(JSON.stringify(listTree));
  list.forEach((item) => {
    getLevel(item);
  });
  function getLevel(node, level = 1) {
    node.level = level;
    if (node.children?.length > 0) {
      node.children.forEach((item) => {
        getLevel(item, level + 1);
      });
    }
  }
  return list;
};

// 截屏
export const screenshot = (element) => {
  return new Promise((resolve, reject) => {
    html2canvas(element)
      .then((canvas) => {
        const dataURL = canvas.toDataURL('image/png');
        canvas.toBlob((blob) => {
          resolve({
            dataURL,
            blob
          });
        });
      })
      .catch((e) => {
        reject(e);
      });
  });
};

// 加密
export const pswEncryption = (data) => {
  let newData = window.btoa(data);
  newData = newData.replace(/\//g, '_a').replace(/\+/g, '_b').replace(/\=/g, '_c');
  return newData;
};

export default {
  timeFormat,
  formatSeconds,
  downloadFile,
  requireImg,
  fullscreen,
  randomCode,
  numberToUppercase,
  getNodeLevel,
  screenshot,
  pswEncryption
};
